<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="老人ID" prop="elderlyId">
        <el-input v-model="queryParams.elderlyId" placeholder="请输入老人ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="menuDate">
        <el-date-picker
          v-model="queryParams.menuDate"
          type="date"
          placeholder="请选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          clearable
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="餐次类型" prop="mealType">
        <el-select v-model="queryParams.mealType" placeholder="请选择餐次类型" clearable @change="handleQuery">
          <el-option label="早餐" :value="1" />
          <el-option label="午餐" :value="2" />
          <el-option label="晚餐" :value="3" />
          <el-option label="加餐" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option label="未处理" :value="0" />
          <el-option label="已处理" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['catering:feedback:add']">
          新增反馈
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['catering:feedback:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['catering:feedback:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['catering:feedback:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="feedbackList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="老人ID" align="center" prop="elderlyId" width="120" />
      <el-table-column label="日期" align="center" prop="menuDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.menuDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="餐次类型" align="center" prop="mealType" width="100">
        <template #default="scope">
          <el-tag :type="getMealTypeTagType(scope.row.mealType)">
            {{ getMealTypeName(scope.row.mealType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="满意度" align="center" prop="satisfactionLevel" width="100">
        <template #default="scope">
          <el-rate v-model="scope.row.satisfactionLevel" disabled show-score text-color="#ff9900" />
        </template>
      </el-table-column>
      <el-table-column label="反馈内容" align="center" prop="feedbackContent" :show-overflow-tooltip="true" />
      <el-table-column label="反馈图片" align="center" prop="feedbackImages" width="120">
        <template #default="scope">
          <image-preview :src="getFullImageUrl(scope.row.feedbackImages)" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" effect="dark">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="回复内容" align="center" prop="responseContent" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['catering:feedback:query']">
            查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['catering:feedback:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="ChatDotRound" @click="handleResponse(scope.row)" v-hasPermi="['catering:feedback:response']">
            回复
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['catering:feedback:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改用餐反馈对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="feedbackRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="老人ID" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人ID" />
        </el-form-item>
        <el-form-item label="日期" prop="menuDate">
          <el-date-picker
            v-model="form.menuDate"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="餐次类型" prop="mealType">
          <el-select v-model="form.mealType" placeholder="请选择餐次类型" style="width: 100%">
            <el-option label="早餐" :value="1" />
            <el-option label="午餐" :value="2" />
            <el-option label="晚餐" :value="3" />
            <el-option label="加餐" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="满意度" prop="satisfactionLevel">
          <el-rate v-model="form.satisfactionLevel" show-score text-color="#ff9900" :max="5" />
        </el-form-item>
        <el-form-item label="反馈内容" prop="feedbackContent">
          <el-input v-model="form.feedbackContent" type="textarea" :rows="4" placeholder="请输入反馈内容" />
        </el-form-item>
        <el-form-item label="反馈图片" prop="feedbackImages">
          <image-upload v-model="form.feedbackImages" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="反馈详情" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="老人ID">{{ viewForm.elderlyId }}</el-descriptions-item>
        <el-descriptions-item label="日期">{{ parseTime(viewForm.menuDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="餐次类型">
          <el-tag :type="getMealTypeTagType(viewForm.mealType)">
            {{ getMealTypeName(viewForm.mealType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="满意度">
          <el-rate v-model="viewForm.satisfactionLevel" disabled show-score text-color="#ff9900" />
        </el-descriptions-item>
        <el-descriptions-item label="处理状态" :span="2">
          <el-tag :type="getStatusTagType(viewForm.status)" effect="dark">
            {{ getStatusName(viewForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="反馈内容" :span="2">
          <div style="white-space: pre-wrap;">{{ viewForm.feedbackContent }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="反馈图片" :span="2">
          <image-preview :src="getFullImageUrl(viewForm.feedbackImages)" :width="200" :height="150" />
        </el-descriptions-item>
        <el-descriptions-item label="回复内容" :span="2" v-if="viewForm.responseContent">
          <div style="white-space: pre-wrap;">{{ viewForm.responseContent }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" v-if="viewForm.updateTime">{{ parseTime(viewForm.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回复对话框 -->
    <el-dialog title="回复反馈" v-model="responseOpen" width="500px" append-to-body>
      <el-form ref="responseRef" :model="responseForm" :rules="responseRules" label-width="100px">
        <el-form-item label="反馈内容" prop="feedbackContent">
          <div style="background-color: #f5f5f5; padding: 10px; border-radius: 4px; margin-bottom: 10px;">
            {{ responseForm.feedbackContent }}
          </div>
        </el-form-item>
        <el-form-item label="回复内容" prop="responseContent">
          <el-input v-model="responseForm.responseContent" type="textarea" :rows="4" placeholder="请输入回复内容" />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-radio-group v-model="responseForm.status">
            <el-radio :value="1">已处理</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitResponse">确 定</el-button>
          <el-button @click="responseOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Feedback">
import { listFeedback, getFeedback, delFeedback, addFeedback, responseFeedback, exportFeedback } from '@/api/catering/feedback'

const { proxy } = getCurrentInstance()

const feedbackList = ref([])
const open = ref(false)
const viewOpen = ref(false)
const responseOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const baseUrl = import.meta.env.VITE_APP_BASE_API;
function getFullImageUrl(url) {
  if (!url) return '';
  // 如果已经是完整的URL（阿里云OSS），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  // 如果是相对路径，拼接baseUrl
  return baseUrl + url;
}

const data = reactive({
  form: {},
  viewForm: {},
  responseForm: {
    status: 1
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderlyId: null,
    menuDate: null,
    mealType: null,
    status: null
  },
  rules: {
    elderlyId: [
      { required: true, message: '老人ID不能为空', trigger: 'blur' }
    ],
    menuDate: [
      { required: true, message: '日期不能为空', trigger: 'change' }
    ],
    mealType: [
      { required: true, message: '餐次类型不能为空', trigger: 'change' }
    ],
    satisfactionLevel: [
      { required: true, message: '满意度不能为空', trigger: 'change' }
    ],
    feedbackContent: [
      { required: true, message: '反馈内容不能为空', trigger: 'blur' }
    ]
  },
  responseRules: {
    responseContent: [
      { required: true, message: '回复内容不能为空', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '处理状态不能为空', trigger: 'change' }
    ]
  }
})

const { queryParams, form, viewForm, responseForm, rules, responseRules } = toRefs(data)

/** 查询用餐反馈列表 */
function getList() {
  loading.value = true
  listFeedback(queryParams.value).then(response => {
    feedbackList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 获取餐次类型名称
function getMealTypeName(mealType) {
  const mealTypeMap = {
    1: '早餐',
    2: '午餐',
    3: '晚餐',
    4: '加餐'
  }
  return mealTypeMap[mealType] || mealType
}

// 获取餐次类型标签样式
function getMealTypeTagType(mealType) {
  const tagTypeMap = {
    1: 'success',
    2: 'warning',
    3: 'info',
    4: 'primary'
  }
  return tagTypeMap[mealType] || ''
}

// 获取状态名称
function getStatusName(status) {
  const statusMap = {
    0: '未处理',
    1: '已处理'
  }
  return statusMap[status] || status
}

// 获取状态标签样式
function getStatusTagType(status) {
  const tagTypeMap = {
    0: 'warning',
    1: 'success'
  }
  return tagTypeMap[status] || ''
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    elderlyId: null,
    menuDate: null,
    mealType: null,
    satisfactionLevel: 5,
    feedbackContent: null,
    feedbackImages: null
  }
  proxy.resetForm('feedbackRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加用餐反馈'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getFeedback(id).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改用餐反馈'
  })
}

/** 查看按钮操作 */
function handleView(row) {
  getFeedback(row.id).then(response => {
    viewForm.value = response.data
    viewOpen.value = true
  })
}

/** 回复按钮操作 */
function handleResponse(row) {
  responseForm.value = {
    id: row.id,
    feedbackContent: row.feedbackContent,
    responseContent: row.responseContent || '',
    status: row.status === 0 ? 1 : row.status
  }
  responseOpen.value = true
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['feedbackRef'].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        // 修改操作
        proxy.$modal.msgError('反馈信息不允许修改')
      } else {
        addFeedback(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 提交回复 */
function submitResponse() {
  proxy.$refs['responseRef'].validate(valid => {
    if (valid) {
      responseFeedback(responseForm.value).then(response => {
        proxy.$modal.msgSuccess('回复成功')
        responseOpen.value = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除用餐反馈编号为"' + ids + '"的数据项？').then(function() {
    return delFeedback(ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('catering/feedback/export', {
    ...queryParams.value
  }, `feedback_${new Date().getTime()}.xlsx`)
}

getList()
</script> 